package com.useOKhttp;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final String url = "http://www.baidu.com";
    private final static String imgUrl = "http://ica.gdcp.cn/service?wdApplication=nr&wdService=getData&wdtest=false&path=/upload/image/20190118/1547824760637005178/wpsA302.tmp.png";
    private final static String phoneUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
    private static final int GET_RESULT = 1001;
    private static final int GET_IMG = 1002;
    private OkHttpClient okHttpClient;
    private EditText edtPhone;
    private TextView txtResult;
    private ImageView ivImg;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        okHttpClient = new OkHttpClient();
        txtResult = findViewById(R.id.txt_result);
        ivImg = findViewById(R.id.iv_img);
        edtPhone = findViewById(R.id.edt_phone);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == GET_RESULT) {
                    String content = (String) msg.obj;
                    txtResult.setText(content);
                    return true;
                } else if (msg.what == GET_IMG) {
                    Bitmap bitmap = (Bitmap) msg.obj;
                    ivImg.setImageBitmap(bitmap);
                    return true;
                }
                return false;
            }
        });

        //异步get
        findViewById(R.id.btn_get).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Request request = new Request.Builder()
                        .url(url)
                        .get()//默认是get请求，可不写
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, "onFailure: " + e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        /*Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                        Message message = Message.obtain();
                        message.what = GET_IMG;
                        message.obj = bitmap;
                        handler.sendMessage(message);*/

                        String content = response.body().string();
                        Log.e(TAG, "onResponse: " + content);
                        Message message = Message.obtain();
                        message.what = GET_RESULT;
                        message.obj = content;
                        handler.sendMessage(message);
                    }
                });
            }
        });

        //同步get
        findViewById(R.id.btn_asyncGet).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Request request = new Request.Builder().url(url).build();
                final Call call = okHttpClient.newCall(request);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Response response = call.execute();
                            String content = response.body().string();

                            Message message = Message.obtain();
                            message.what = GET_RESULT;
                            message.obj = content;
                            handler.sendMessage(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        findViewById(R.id.btn_post).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = edtPhone.getText().toString();
                RequestBody requestBody = new FormBody.Builder()
                        .add("mobileCode", phone)
                        .add("userID", "")
                        .build();
                Request request = new Request.Builder().url(phoneUrl).post(requestBody).build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, "onFailure: " + e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String content = response.body().string();
                        Log.e(TAG, "onResponse: " + content);
                        Message message = Message.obtain();
                        message.what = GET_RESULT;
                        message.obj = content;
                        handler.sendMessage(message);
                    }
                });
            }
        });

        findViewById(R.id.btn_phoneGet).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = edtPhone.getText().toString();
                String phoneUrlstr = phoneUrl.concat("?mobileCode=").concat(phone).concat("&userID=");
                Request request = new Request.Builder().url(phoneUrlstr).build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, "onFailure: " + e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String content = response.body().string();
                        Log.e(TAG, "onResponse: " + content);
                        Message message = Message.obtain();
                        message.what = GET_RESULT;
                        message.obj = content;
                        handler.sendMessage(message);
                    }
                });
            }
        });
    }
}
